<template>
  <div class="outer">
    <span>价格：</span>
    <span class="money">{{money.toFixed(2)}}</span>
    <button @click="discount">打折</button>
  </div>
</template>
 
<script setup lang='ts'>
import { ref } from 'vue';

let money = ref<number>(2999.00)

function animation(duration: number, from: number, to: number, fun: Function) {
  const dis: number = to - from  // 变化间隔
  const speed: number = dis / duration  // 变化的速度
  const startTime: number = Date.now()  // 起始时间
  let val: number = from  // 当前的值
  fun(val)

  function _run(): void {
    const now: number = Date.now()  // 当前时间
    const time: number = now - startTime  // 时间间隔
    if (time >= duration) {
      val = to
      fun(val)
      return
    }
    const d: number = time * speed  // 变化间隔
    val = from + d  // 当前的值
    fun(val)
    requestAnimationFrame(_run)
  }

  requestAnimationFrame(_run)
}

// 打折
const discount = () => {
  animation(1000, money.value, 299, (val: number) => {
    money.value = parseFloat(val.toFixed(2))
  })
}
</script>
 
<style lang='scss' scoped>
.outer {
  width: 300px;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;

  .money {
    background-color: #acd2ff;
    padding: 10px 6px;
    border-radius: 6px;
  }

  button {
    width: 70px;
    height: 50px;
    background-color: #3793ff;
    border: none;
    outline: none;
    font-size: 18px;
    border-radius: 6px;
    color: white;
    cursor: pointer;

    &:hover {
      background-color: rgba(55, 147, 255, .9);
    }
  }
}
</style>